let messageCount = 0;
const MAX_MESSAGES_BEFORE_EXPORT = 100;

/**
 * 监听来自内容脚本的消息
 * @param {Object} request - 请求对象
 * @param {string} request.type - 消息类型
 * @param {Object} request.data - 消息数据
 * @param {Object} sender - 发送者信息
 * @param {function} sendResponse - 响应回调函数
 * @returns {boolean} 返回true表示异步响应
 */
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'NEW_MESSAGE') {
    storeMessage(request.data)
      .then(() => {
        messageCount++;
        if (messageCount >= MAX_MESSAGES_BEFORE_EXPORT) {
          return exportData();
        }
      })
      .catch(err => {
        console.error('Message processing error:', err);
      });
  }
  return true;
});

/**
 * 将消息存储到chrome.storage.local中
 * @param {Object} message - 要存储的消息对象
 * @returns {Promise<void>} 存储成功时resolve，失败时reject
 */
async function storeMessage(message) {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get(['messages'], (result) => {
      const messages = result.messages || [];
      messages.push(message);
      
      chrome.storage.local.set({ messages }, () => {
        if (chrome.runtime.lastError) {
          reject(chrome.runtime.lastError);
        } else {
          resolve();
        }
      });
    });
  });
}

/**
 * 导出存储的消息为JSON文件并下载
 * 文件名为telegram_data_时间戳.json
 * 导出后会清空存储的消息
 * @returns {Promise<void>} 导出成功时resolve，失败时reject
 */
async function exportData() {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get(['messages'], (result) => {
      const messages = result.messages || [];
      if (messages.length === 0) {
        resolve();
        return;
      }

      const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
      const filename = `telegram_data_${timestamp}.json`;
      const blob = new Blob([JSON.stringify(messages, null, 2)], {type: 'application/json'});
      const url = URL.createObjectURL(blob);

      chrome.downloads.download({
        url: url,
        filename: filename,
        saveAs: false
      }, () => {
        URL.revokeObjectURL(url);
        if (chrome.runtime.lastError) {
          reject(chrome.runtime.lastError);
        } else {
          // 导出后清空存储
          chrome.storage.local.set({ messages: [] }, () => {
            messageCount = 0;
            resolve();
          });
        }
      });
    });
  });
}
